/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Util.js
 * @path:   js/Ancestor/
 * @desc:
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
qui(function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/

    Ancestor.Util = (function() {

        Date.prototype.format = function (format) {
        var o = {
                  "M+" : this.getMonth() + 1, //month
                  "d+" : this.getDate(), //day
                  "h+" : this.getHours(), //hour
                  "m+" : this.getMinutes(), //minute
                  "s+" : this.getSeconds(), //second
                  "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
                  "S" : this.getMilliseconds() //millisecond
              }

              if (/(y+)/.test(format)) {
                  format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
              }

              for (var k in o) {
                  if (new RegExp("(" + k + ")").test(format)) {
                      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                  }
              }
              return format;
          };

        // 组装 sign
        var authorization = function(options) {
            var rawSign = options.url + options.clientTime + Ancestor.Config.EPG_AUTH.key;
            return md5(rawSign);
        };

        /**
         * 设置截图编辑的整体，包括截图、幻灯片、上传三个部分
         * @param $imgcrop Object 整体的DOM结构，jQuery Object
         * @param images Array<String> 初始化用的图片URL数组
         * @param width 如果有幻灯片的话，幻灯片部分的宽度
         */
        var imageCrop = function($imgcrop) {
            // try{
            var $slideshow = $imgcrop.find('.slideshow');
            var $enableBtn = $imgcrop.find('button.button-enable');
            var $uploadBtn = $imgcrop.find('input.uploadButton');
            var $btnOnline = $imgcrop.find('button.button-online');
            var gallery, t, flag;
            // 设置下面的缩略图
            $slideshow.gallery({
                thumbnail: '.item',
                prevButton: $slideshow.find('button.left'),
                nextButton: $slideshow.find('button.right')
            });
            gallery = $slideshow.data('gallery');
            t = gallery.totalItems;
            // 设置上传图片按钮
            if ($uploadBtn.length) {
                $uploadBtn.uploadDialog({
                    gallery: $imgcrop.find('.gallery'),
                    onStart: function() {
                        gallery.update();
                        gallery.scrollTo(t);
                    }
                });
            }
            $(window).resize(function(e) {
                gallery.update();
            });
            // 设置截图控件
            $imgcrop.imageCrop({
                'gallery': '.gallery',
                'cropimg': '.cropimg',
                'results': '.results'
            });
            // 设置激活按钮
            if ($('#_entityId').val()) {
                $enableBtn.click(function(e) {
                    $imgcrop.data('imageCrop').enable();
                    $enableBtn.attr('disabled', true);
                    gallery.scrollTo(0);
                });
                $imgcrop.data('imageCrop').disable();
                $enableBtn.attr('disabled', false);
            } else {
                $imgcrop.data('imageCrop').enable();
                $enableBtn.attr('disabled', true);
                $enableBtn.hide();
            }
          $imgcrop.find('.header input').enable();
            if ('1' === $('#ThriftVideoMakeStatus').val() && '1' != $('#entityType').val()) {
                $btnOnline.show();
            } else {
                $btnOnline.hide();
            }
            // 设置在线视频截图
            /*
            if ($btnOnline.length) {
                $('#AlbumEditVideoShot').videoShot({
                    onFinish: function(area, images) {
                        var data = [];
                        $.each(images, function(index, image) {
                            data.push({
                                shot: true,
                                url: image,
                                area: area
                            });
                        });
                        $imgcrop.data('imageCrop').addImages(data);
                    }
                });
                $btnOnline.click(function(e) {
                    $('#AlbumEditVideoShot').dialog('open');
                });
            }
            */

            // }catch(e){}
        };


        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function(textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function() {
                    t(this);
                },
                propertychange: function() {
                    t(this);
                },
                keyup: function() {
                    t(this);
                }
            }).trigger('keyup');
            $des.keyup();
        };

        getParam = function($obj) {

            var $container = $obj;
            var params = {};
            var $form = $obj;

            var $elements = $.makeArray($form.prop('elements')).filter(function() {
                return true; //this.name; 
            });

            var name;
            var key;
            $.each($elements, function() {
                name = this.name;
                if (name) {

                    if (this.type == 'radio') {
                        params[name] = $('input[name="' + name + '"]:checked').val() || '';
                    } else
                        params[name] = $.trim($(this).val()) || '';

                }

            });

            params['logoUrl'] = imageObject($obj);
            return params;

        };

        imageObjectEcho = function($form, value) {

            if (value) {
                value = ('object' == typeof(value) ? value : JSON.parse(value || '[]'));
            } else {
                value = null;
            }
            if (!value) {
                return;
            }

            var imageObject = value;
            var filterType = function(type) {
                var imageData = null;
                $.each(imageObject, function(index, value) {
                    if (value.useType == type) {
                        imageData = value;
                    }
                });
                return imageData;
            };
            var spathToURL = function(images, spath) {
                var url = null;
                $.each(images, function(index, image) {
                    if (spath === image.spath) {
                        url = image.url;
                    }
                });
                return url;
            };

            $form.find('div.module-container-screen-crop').each(function(index, element) {
                var $croparea = $(this);
                var imageCrop = $croparea.data('imageCrop');
                var useType = 699; //parseInt($croparea.find('input[name="useType"]').val(), 10);
                var imageData = filterType(useType);
                var imageRank = imageData && imageData.contentRank ? imageData.contentRank : 0;
                var images = [],
                    results = {};

                if (!imageData) {
                    return;
                }

                // 回显图片分级的选项
                $croparea.find('input[name^="contentRank"]').each(function(key, value) {
                    value.checked = (imageRank == value.value);
                });

                $.each(imageData.materials, function(index, material) {
                    //images.push(material.bigThumbUrl || material.location);
                    // todo: type
                    images.push({
                        spath: material.location,
                        url: material.url,
                        data: material
                    });
                });
                $.each(imageData.images, function(index, image) {
                    var scale = image.editInfo.scale;
                    var cutPosition = image.editInfo.cutPosition.split(',');
                    var width = scale.substring(0, scale.indexOf(':'));
                    var height = scale.substring(scale.indexOf(':') + 1);
                    results[width + '-' + height] = {
                        spath: image.materialLocation,
                        imgsrc: spathToURL(images, image.materialLocation),
                        w: width,
                        h: height,
                        x1: parseInt(cutPosition[0], 10),
                        y1: parseInt(cutPosition[1], 10),
                        x2: parseInt(cutPosition[0], 10) + parseInt(cutPosition[3], 10),
                        y2: parseInt(cutPosition[1], 10) + parseInt(cutPosition[2], 10),
                        data: image
                    };
                });
                imageCrop.addImages(images, function() {
                    imageCrop.setValue(results);
                });
            });
        };


        imageObject = function($form) {
            var imageObject = [];
            $form.find('div.module-container-screen-crop').each(function(index, element) {
                var $croparea = $(this);
                var useType = parseInt($croparea.find('input[name="useType"]').val(), 10);
                var contentRank = parseInt($croparea.find('input[name^="contentRank"]:checked').val(), 10) || 0; // 默认图片分级是无分级，0
                var testFlag = 0;
                var imageData = {
                    materials: [],
                    images: [],
                    useType: 699, //useType,
                    contentRank: contentRank // 图片分级的需求，默认是无分级
                };
                $croparea.find('.gallery img').each(function(index, material) {
                    var $material = $(material);
                    if (true === $material.data('loading')) {
                        return;
                    }
                    var tmp = $material.data('data') || {
                        // @todo
                        'location': $material.data('spath') || '',
                        'url': $material.attr('src'),
                        'fromType': $material.data('type'),
                        'area': 'bj', //$material.data('area'),
                        'width': $material.data('width'),
                        'height': $material.data('height')
                    };
                    imageData.materials.push(tmp);
                    testFlag++;
                });
                $.each($croparea.data('imageCrop').getValue(), function(index, value) {
                    var tmp = $.extend(value.data, {
                        materialLocation: value.spath || value.imgsrc || '',
                        editInfo: {
                            cutPosition: [value.x1, value.y1, value.y2 - value.y1, value.x2 - value.x1].join(','),
                            scale: value.w + ':' + value.h
                        }
                    });
                    imageData.images.push(tmp);
                    //testFlag |= Math.pow(2, value.index);
                });
                var type = $form.find('input[name="entityType"]').val();
                if (('0' == type && (parseInt($form.find('input[name="video.id"]').val(), 10) > 0))
                    // 如果是节目且专辑id禁用表示编目修改
                    || ('1' === type && (parseInt($form.find('input[name="album.id"]').val(), 10) > 0))
                    // 如果是专辑有#_entityId表示修改
                    || ($form.find('input[name=pilosityType]').val() && $form.find('input[name=baseId]').val())
                    // 如果是一文多发有pilosity且有baseId表示修改
                ) {
                    // 节目，专辑, 一文多发，兼容旧的，修改的时候不验证截图
                    testFlag = 99;
                }
                $croparea.find('input[name="_image_crop_' + useType + '"]').val(testFlag);
                imageObject.push(imageData);
            });
            return JSON.stringify(imageObject);
        };


        getUrlId = function(name) {

            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return r[2];
            return null;
        };

        fillFieldNameWhenChangeSelect = function($form, elClazzName, fieldClazzName) {
            $form.find('.' + elClazzName).on('change', function() {
                var value = $(this).val();
                var $input = $(this).closest('.control-group').find('.' + fieldClazzName);
                $input.attr('name', value);
            });
        };


        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function(textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function() {
                    t(this);
                },
                propertychange: function() {
                    t(this);
                },
                keyup: function() {
                    t(this);
                }
            });
            $des.keyup();
        };

        var getUploadFiles = function(options, isNew) {
            if (isNew && isNew === true) {
                return new Ancestor.Upload(options);
            }
            if (!uploadFiles) {
                uploadFiles = new Ancestor.Upload(options);
            } else {
                uploadFiles.update(options);
            }
            return uploadFiles;
        };

        var isNormal = function(user) {

            return true;
        };



        // 打开对话框
        var openDlg = function(obj, title, width, height) {

            height = height || 'auto';
            var $container = obj;

            $container.dialog({
                title: title,
                appendTo: null,
                modal: true,
                width: width,
                height: height,
                position: ['top', 'top+20'],

                open: function() {
                    $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                },
                close: function() {

                }
            });
        };

        var highlight = function(data, key, term) {
            data.forEach(function(item, i) {
                key = key || 'label';
                var label = item[key];
                if (!label || !term) {
                    return;
                }
                item[key] = (item[key] + '').replace(new RegExp('(' + term + ')', 'i'), '<b>$1</b>');
                // 高亮未输入部分
                // if (label.toLowerCase().indexOf(term.toLowerCase()) == 0) {
                //     item[key] = item[key].substr(0, term.length)
                //                   + '<b>'
                //                   + item[key].substr(term.length) + '</b>';
                // }
            });
        };

        var updateParamsBySettings = function(params, entity) {
            if (!params) {
                params = {};
            }

            if (entity.checkPublishType == 1) {
                params["filter_EQI_pagePublishStatus"] = 1;
            }
            if (entity.checkCopyRightType == 1) {
                params["filter_GTI_copyrightOwnerId"] = 0;
            }
            if (entity.checkBossType == 0) {
                params["filter_INI_isPurchase"] = "0,-100";
            } else if (entity.checkBossType == 1) {
                params["filter_INI_isPurchase"] = "1,2";
            }
            var platformTypeResponse = Ancestor.Config.PLATFORM_TYPE;
            $.each(platformTypeResponse, function(i, element) {
                //   params["region_" + element.val] = 0;
                if (entity.regionLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["region_" + element.val] = 1;
                }
            });
            var platformReferResponse = Ancestor.Config.PLATFORM_REFER;
            $.each(platformReferResponse, function(i, element) {
                //   params["filter_EQI_" + element.val] = 0;
                if (entity.onlineLimitArr.indexOf(parseInt(element.key)) != -1) {
                    params["filter_EQI_" + element.val] = 1;
                }

            });
            console.log(" params:" + JSON.stringify(params));

            return params;
        };

        var createSuggest = function(el, options) {
            options = $.extend(true, {
                // 是否自动选择地一条
                autoFocus: true,
                // 选中input时请求
                focusSearch: false,
                sortBy: false,
                // 是否校验结果
                validate: false,
                // 多条时是否验证必有数据
                multipleValid: false,
                // 是否高亮
                highlight: true,
                // 是否onblur时清空无效结果
                clearInvalid: true,
                noResult: '对不起，没有这个结果',
                valueKey: 'id',
                parseValue: function() {
                    var val = this.element.val();
                    var ret = [];
                    if (val) {
                        var items = val.split(';');
                        $.each(items, function(i, item) {
                            item = item.split(',');
                            ret.push({
                                value: item[1],
                                id: item[0],
                                label: item[1]
                            });
                        });
                    }
                    this._value('');
                    return ret;
                },
                create: function(event, ui) {
                    $(this).autocomplete('init');

                    if (options.focusSearch) {
                        $(el).on('focus', function() {
                            if ($.trim(this.value) !== '') {
                                $(this).autocomplete('search');
                            }
                        });
                    }
                },
                otherParam: $.extend({}, options.params),
                source: function(request, response) {
                    var self = this;
                    var term = $.trim(request.term);
                    var result = [];
                    if (!term) {
                        return null;
                    }
                    self.getResultData = function() {
                        return result;
                    };
                    var options = this.options;
                    var dataProcess = options.process || process;
                    var param = {};
                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }
                    param = $.extend(true, options.otherParam, param);

                    //根据dom上定义的sugg-filter过滤项增加过滤参数
                    //sugg-filter中的过滤项以逗号分隔
                    var filterStr = $(el).attr('sugg-filter');
                    if ($.trim(filterStr)) {
                        var filters = $.trim(filterStr).split(',');
                        if (filters && filters.length > 0) {
                            for (var i = 0, l = filters.length, filter; i < l; i++) {
                                filter = filters[i].split('=');
                                if (filter.length == 2) {
                                    param[filter[0]] = filter[1];
                                }
                            }
                        }
                    }

                    var url = options.url;
                    var getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(this, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }

                    var fetchData = function() {
                        Ancestor.Dao.getSuggestData(url, param, function(json) {
                            var ret = dataProcess.call(self, json, term);

                            var runNext = function(ret) {
                                if ($.isArray(options.sortBy)) {
                                    sortBy.apply(self, [ret].concat(options.sortBy));
                                } else if ($.isFunction(options.onSortBy)) {
                                    options.onSortBy.apply(self, [ret, term]);
                                }

                                if (options.highlight) {
                                    if ($.isFunction(options.onHighlight)) {
                                        options.onHighlight.apply(self, [ret, term]);
                                    } else {
                                        highlight(ret, null, term);
                                    }
                                }
                                result = ret;
                                if ($.isFunction(options.onLoad)) {
                                    options.onLoad.apply(self, [result, term]);
                                }
                                response(result);
                            };

                            if (options.needFetchMore) {
                                options.fetchMore(ret, runNext);
                            } else {
                                runNext(ret);
                            }
                        });
                    };

                    if (options.needPreProcess) {
                        var channelId = Com.url.getParameter("id");
                        Ancestor.Dao.platSettings({
                            channelId: channelId
                        }, function(json) {
                            if (json.code === 'A00000') {
                                param = updateParamsBySettings(param, json.data);
                                fetchData();
                            }
                        });
                    } else {
                        fetchData();
                    }


                }
            }, options);

            /* ui-front ui-suggest*/
            return $(el).wrap('<span class="ui-front ui-suggest" ></span>').autocomplete(
                options).on('autocompleteresponse', function(event, ui) {
                var content = ui.content;
                $(this).autocomplete('validate', content);
            }).on('autocompleteselect', function(event, ui) {


                //////////////////suggest选择后回显设置/////////////////////
                //  ui.item.value=ui.item.name;


                return $(this).autocomplete('setValue', ui.item);

            }).on('autocompletesearch', function(event, ui) {
                //支持多选
                return $(this).autocomplete('multiplesearch');
            });
        };

        var qitan = function(el, options) {

            var tpl = '<div><div class="contract-item">' +
                '<span class="contract-width80">${resourceId}</span>' +
                '<span class="contract-width250">{{html name}}</span>' +
                '<span class="contract-width80">${addDate}</span>' +
                '</div></div>';

            var title = {
                resourceId: '评论ID',
                name: '评论名称',
                addDate: '创建时间'
            };

            var getHtmlByData = function(data) {
                var htmls = [];
                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);
            createSuggest(el, $.extend(true, {

                url: 'http://api.t.iqiyi.com/qx_api/resource/get_id_by_name',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                otherParam: $.extend({
                    'page_size': 10,
                    'resource_type': $(el).data('type') || 1
                }, options.params),
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'name': term
                    };
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data.ids;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, item, {
                                label: item.name,
                                value: item.resourceId,
                                id: item.resourceId
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-qitan');
        };


        var universalCodeCreateSuggest = function(el, options) {
            options = $.extend(true, {
                // 是否自动选择地一条
                autoFocus: true,
                // 选中input时请求
                focusSearch: false,
                sortBy: false,
                // 是否校验结果
                validate: false,
                // 多条时是否验证必有数据
                multipleValid: false,
                // 是否高亮
                highlight: true,
                // 是否onblur时清空无效结果
                clearInvalid: true,
                noResult: '对不起，没有这个结果',
                valueKey: 'id',
                parseValue: function() {
                    var val = this.element.val();
                    var ret = [];
                    if (val) {
                        var items = val.split(';');
                        $.each(items, function(i, item) {
                            item = item.split(',');
                            ret.push({
                                value: item[1],
                                id: item[0],
                                label: item[1]
                            });
                        });
                    }
                    this._value('');
                    return ret;
                },
                create: function(event, ui) {
                    $(this).autocomplete('init');

                    if (options.focusSearch) {
                        $(el).on('focus', function() {
                            if ($.trim(this.value) !== '') {
                                $(this).autocomplete('search');
                            }
                        });
                    }
                },
                otherParam: $.extend({}, options.params),
                source: function(request, response) {
                    var self = this;
                    var term = $.trim(request.term);
                    var result = [];
                    if (!term) {
                        return null;
                    }
                    self.getResultData = function() {
                        return result;
                    };
                    var options = this.options;
                    var dataProcess = options.process || process;
                    var param = {};
                    if (!options.ignoreWord) {
                        //传递 word  term
                        param = {
                            word: term
                        };
                    }
                    param = $.extend(true, options.otherParam, param);

                    //根据dom上定义的sugg-filter过滤项增加过滤参数
                    //sugg-filter中的过滤项以逗号分隔
                    var filterStr = $(el).attr('sugg-filter');
                    if ($.trim(filterStr)) {
                        var filters = $.trim(filterStr).split(',');
                        if (filters && filters.length > 0) {
                            for (var i = 0, l = filters.length, filter; i < l; i++) {
                                filter = filters[i].split('=');
                                if (filter.length == 2) {
                                    param[filter[0]] = filter[1];
                                }
                            }
                        }
                    }

                    var url = options.url;
                    var getParam = options.getParam;
                    if (getParam) {
                        if ($.isFunction(options.getParam)) {
                            param = $.extend(true, param, getParam.call(this, term));
                        } else if ($.isPlainObject(getParam)) {
                            param = $.extend(true, param, getParam);
                        }
                    }
                    Ancestor.Dao.getuniversalCodeData(url, param, function(json) {
                        var ret = dataProcess.call(self, json, term);
                        if ($.isArray(options.sortBy)) {
                            sortBy.apply(self, [ret].concat(options.sortBy));
                        } else if ($.isFunction(options.onSortBy)) {
                            options.onSortBy.apply(self, [ret, term]);
                        }

                        if (options.highlight) {
                            if ($.isFunction(options.onHighlight)) {
                                options.onHighlight.apply(self, [ret, term]);
                            } else {
                                highlight(ret, null, term);
                            }
                        }
                        result = ret;
                        if ($.isFunction(options.onLoad)) {
                            options.onLoad.apply(self, [result, term]);
                        }
                        response(result);
                    });

                }
            }, options);

            /* ui-front ui-suggest*/
            return $(el).wrap('<span class="ui-front ui-suggest" ></span>').autocomplete(
                options).on('autocompleteresponse', function(event, ui) {
                var content = ui.content;
                $(this).autocomplete('validate', content);
            }).on('autocompleteselect', function(event, ui) {
                ui.item.value = ui.item.code;
                return $(this).autocomplete('setValue', ui.item);

            }).on('autocompletesearch', function(event, ui) {
                //支持多选
                return $(this).autocomplete('multiplesearch');
            });
        }

        var universalCode = function(el, options) {

            var tpl = '<div><div class="contract-item">' +
                '<span class="contract-width250">${code}</span>' +
                '<span style="border-right:none;">${name}</span>' +
                '</div></div>';

            var title = {
                code: '直播频道首拼音',
                name: '直播频道名称',
            };

            var getHtmlByData = function(data) {
                var htmls = [];
                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);

            universalCodeCreateSuggest(el, $.extend(true, {

                url: '/api/channel/codelist',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'key': term
                    };
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data, function(item) {
                            ret.push($.extend(true, item, {
                                name: item.name,
                                code: item.code,
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-qitan');
        };



        var qitanSuggest = function($inputs, options) {

            $inputs.each(function(index, element) {
                var self = this;
                qitan($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.id);
                        //console.log( $input.data('value'));
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };

        var universalCodeSuggest = function($inputs, options) {

            $inputs.each(function(index, element) {
                var self = this;
                universalCode($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.code);
                        //console.log($input.data('value'));
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };



        var alternatePlayCollection = function(el, options) {

            var tpl = '<div class="contract-item">' +
                '<span class="contract-width100" style="color:${needAlert}">${qipuId}</span>' +
                '<span class="contract-width150" style="color:${needAlert}">${displayName}</span>' +
                '<span class="contract-width60" style="color:${needAlert}">${channelName}</span>' +
                '<span class="contract-width120" style="color:${needAlert}">${copyrightEndTime}</span>' +
                '<span class="contract-width80" style="color:${needAlert}">${isPurchase}</span>' +
                '<span class="contract-width80" style="color:${needAlert}">${pagePublishStatus}</span>' +
                '</div>';

            var _ppsClientArr = [
                "ANDRIOD_PPSControl",
                "ANDROID_PAD_PPSControl",
                "IOS_JAILBREAK_PPSControl",
                "IPAD_PPSControl",
                "IPHONE_PPSControl",
                "MAC_PPSControl",
                "PC_CLIENT_PPSControl",
                "WIN8_PPSControl",
                "WINDOWS_PHONE_PPSControl"
            ];

            var _platClientArr = [
                "ANDRIOD_PPS",
                "ANDROID_PAD_PPS",
                "IOS_JAILBREAK_PPS",
                "IPAD_PPS",
                "IPHONE_PPS",
                "MAC_PPS",
                "PC_CLIENT_PPS",
                "WIN8_PPS",
                "WINDOWS_PHONE_PPS"
            ];

            var platformRefer = "platformRefer",
                platSettings = "platSettings",
                platforms = "platforms";

            var title = {
                qipuId: '奇谱ID',
                displayName: '显示名称',
                channelName: '频道',
                copyrightEndTime: '版权到期时间',
                isPurchase: '是否付费',
                pagePublishStatus: '发布状态'
            };

            var checkPlatforms = [];
            Ancestor.Dao.getType({
                type: 'PlayPlatform'
            }, function(json) {
                if (json.code == 'A00000') {
                    Ancestor.Config.PLATFORM_TYPE = json.data;
                    checkPlatforms = json.data;
                } else {
                    console.log('Fetch PlayPlatform failed');
                }
            });


            Ancestor.Dao.getType({
                type: 'PlatformRefer'
            }, function(json) {
                if (json.code == 'A00000') {
                    Ancestor.Config.PLATFORM_REFER = json.data;
                } else {
                    console.log('Fetch PlayPlatform failed');
                }
            });

            var decodePlayPlatform = function(elementChild) {
                var locationControl = null;
                var platformObject = {
                    platName: null,
                    locationArr: []
                }
                platformObject.platName = elementChild["play_platform"];
                platformObject.status = 'online';
                if (elementChild["default_control"] != null) {
                    if ("ONLINE" != elementChild["default_control"]["availabe_status"]) {
                        platformObject.status = "offline";
                    }
                }
                if ($.isArray(elementChild["region_control"])) {
                    $.each(elementChild["region_control"], function(indexRegion, regionElement) {
                        if ($.isArray(regionElement["location"])) {
                            $.each(regionElement["location"], function(j, child) {
                                if(child.hasOwnProperty("province_id")){
                                    if (child["province_id"] != 95 && child["province_id"]  != 148 && child["province_id"]  != 228) {
                                        locationControl = regionElement["location_control"];
                                        if (locationControl != null && "ONLINE" != locationControl["availabe_status"]) {
                                            platformObject.locationArr.push(child["province_id"]);
                                            console.log("break regionElement location");
                                        }
                                    }
                                }
                            })
                        }
                    })
                }
                return platformObject;
            };

            var checkPPSClient = function(data) {
                if (data.qipuId == '奇谱ID') {
                    data['needAlert'] = 0;
                    return data;
                }

                var ppsCheckList = [];
                $.each(_ppsClientArr, function(i, ppsKey) {
                    if (!data.hasOwnProperty(ppsKey) || data[ppsKey] == 0) {
                        ppsCheckList.push(ppsKey);
                    }
                });

                if (ppsCheckList.length > 0) {
                    data['needAlert'] = 'red';
                } else {
                    data['needAlert'] = 'black';
                }
                return data;
            };

            var checkQipuData = function(data) {
                var playControlArr = data.QIPUDATA.access_play_control;
                if ($.isArray(playControlArr)) {
                    var temp = {};
                    $.each(playControlArr, function(index, elementChild) {
                        var platformObject = decodePlayPlatform(elementChild);
                        if (platformObject.platName != null) {
                            temp[platformObject.platName] = platformObject;
                        }
                    });

                    var qipuPlatformData = [];
                    var qipuRegionData = [];
                    var hintMsgObj = {
                        missQIYIClient: false,
                        missPPSClient: false,
                        missQIYIRegion: false,
                        missPPSRegion: false
                    };
                    $.each(checkPlatforms, function(index, element) {
                        var ppsFlag = element.val.indexOf("PPS") !== -1;
                        if (!temp.hasOwnProperty(element.val) || temp[element.val].status != "online") {
                            qipuPlatformData.push(element.val);
                            if (ppsFlag) {
                                hintMsgObj.missPPSClient = true;
                            } else {
                                hintMsgObj.missQIYIClient = true;
                            }
                        }
                        if (temp.hasOwnProperty(element.val) && temp[element.val].locationArr.length > 0) {
                            qipuRegionData.push(element.val);
                            if (ppsFlag) {
                                hintMsgObj.missPPSRegion = true;
                            } else {
                                hintMsgObj.missQIYIRegion = true;
                            }
                        }
                    });

                    if (hintMsgObj.missPPSClient || hintMsgObj.missQIYIClient) {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.RED;
                    } else if (hintMsgObj.missPPSRegion || hintMsgObj.missQIYIRegion) {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.ORANGE;
                    } else {
                        data['needAlert'] = Ancestor.Config.APC_WARNING.NORMAL;
                    }

                }

                return data;
            };

            var getHtmlByData = function(data) {

                if (typeof(data.copyrightEndTime) == "number" || typeof(data.copyrightBeginTime) == "number") {

                    if (data.copyrightEndTime == '-100' || data.copyrightBeginTime == '-100') {
                        data.copyrightEndTime = "永久版权";
                    } else if (new Date() > data.copyrightEndTime || new Date() < data.copyrightBeginTime) {
                        data.copyrightEndTime = "过期";
                    } else {
                        data.copyrightEndTime = Com.date.format(new Date(data.copyrightEndTime), "yyyy-MM-dd hh:mm:ss");
                    }
                }

                //if(data.copyrightEndTime=="过期")
                //  return '';

                switch (data.isPurchase) {
                    case 0:
                    case -100:
                        data.isPurchase = "免费";
                        break;
                    case 1:
                        data.isPurchase = "收费";
                        break;
                    case undefined:
                        data.isPurchase = ""
                        break;

                    default:
                        data.isPurchase = data.isPurchase + ""
                }

                switch (data.pagePublishStatus) {
                    case 0:
                        data.pagePublishStatus = "未发布";
                        break;
                    case 1:
                        data.pagePublishStatus = "已发布";
                        break;
                    case 2:
                        data.pagePublishStatus = "页面下线";
                        break;
                    case 3:
                        data.pagePublishStatus = "页面备用"
                        break;
                    case undefined:
                        data.pagePublishStatus = ""
                        break;

                    default:
                        data.pagePublishStatus = data.pagePublishStatus + "";
                }

                var htmls = [];
                data['needAlert'] = Ancestor.Config.APC_WARNING.NORMAL;

                if (data.hasOwnProperty('QIPUDATA')) {
                    data = checkQipuData(data);
                } else {
                    data = checkPPSClient(data);
                }

                var htmlStr = $('<div></div>').html($(tpl).tmpl(data));

                return htmlStr.html();
            };
            var titleHtml = getHtmlByData(title);
            createSuggest(el, $.extend(true, {

                //url: 'http://lego.iqiyi.com/suggest/simple-video-area',
                url: 'http://lego.iqiyi.com/apis/search/search-area',
                ignoreWord: true,
                header: titleHtml,
                validate: true,
                needFetchMore: true,
                needPreProcess: true,
                otherParam: $.extend({
                    t: 0,
                    filter_GTL_qipuId: 0,
                    //filter_EQI_contentType:1,
                    //'page.orderBy': "createTime",
                    //'page.order': "desc",
                    filter_GEL_duration: 30000,
                    //filter_EQI_pagePublishStatus:1,
                    //filter_INI_isPurchase : "0,-100",
                    //filter_GTI_copyrightOwnerId : 0,
                    //filter_EQI_PadIosControl:1,
                    //filter_EQI_PhoneAndroidControl:1,
                    //filter_EQI_PhoneIosControl:1,
                    //filter_EQI_PcControl:1,
                    //filter_EQI_TvControl:1,
                    //filter_EQI_PcClientControl:1,
                    //filter_EQI_H5Control:1,
                    //filter_EQI_PadAndroidControl:1,
                    //filter_EQI_PadWebControl:1,
                    //region:1,
                    'page.pageSize': 10
                        //                    filter_EQI_ANDRIOD_PPSControl: 1,
                        //                    filter_EQI_ANDROID_PAD_PPSControl: 1,
                        //                    filter_EQI_IOS_JAILBREAK_PPSControl: 1,
                        //                    filter_EQI_IPAD_PPSControl: 1,
                        //                    filter_EQI_IPHONE_PPSControl: 1,
                        //                    filter_EQI_MAC_PPSControl: 1,
                        //                    filter_EQI_PC_CLIENT_PPSControl: 1,
                        //                    filter_EQI_WIN8_PPSControl: 1,
                        //                    filter_EQI_WINDOWS_PHONE_PPSControl: 1,
                        //                    needCookie: true

                    //   pps region 限制
                    //region_ANDROID_PAD_PPS:0,
                    //region_WIN8_PPS:0,
                    //region_MAC_PPS:0,
                    //region_WINDOWS_PHONE_PPS:0,
                    //region_ANDRIOD_PPS:0,
                    //region_IOS_JAILBREAK_PPS:0,
                    //region_IPAD_PPS:0,
                    //region_IPHONE_PPS:0,
                    //region_PC_CLIENT_PPS:0,
                    //   qiyi region 限制
                    //region_ANDROID_PAD_IQIYI:1,
                    //region_ANDROID_PHONE_IQIYI:1,
                    //region_H5_QIYI:1,
                    //region_IOS_PAD_IQIYI:1,
                    //region_IOS_PHONE_IQIYI:1,
                    //region_PAD_WEB_QIYI:1,
                    //region_PC_CLIENT_IQIYI:1,
                    //region_PC_QIYI:1,
                    //region_TV_IQIYI:1,
                }, options.params),
                getParam: function(term) {
                    term = $.trim(term);
                    return {
                        'filter_LIKES_displayName': term
                    };
                },

                fetchMore: function(data, callback) {
                    var self = this;
                    self.count = 0;
                    self.ret = [];
                    self.data = data;
                    $.each(data, function(i, item) {
                        Ancestor.Dao.getQipuDataById(item, function(json, t) {
                            if (json) {
                                t.QIPUDATA = json;
                            }
                            self.ret.push(t);
                            self.count++;
                            if (self.count == self.data.length) {
                                callback(self.ret);
                            }
                        });
                    });
                },
                process: function(json) {
                    if (json.data) {
                        var data = json.data;
                        if (!data) {
                            return [];
                        }
                        var ret = [];
                        $.map(data.result, function(item) {
                            ret.push($.extend(true, item, {
                                name: item.displayName,
                                id: item.qipuId
                            }));

                        });
                        return ret;
                    }
                    return [];
                },
                onHighlight: function(data, term) {
                    highlight(data, 'dataName', term);
                },
                template: function(item) {
                    return getHtmlByData(item);
                }
            }, options)).parent().addClass('ui-backup');
        };

        var alternatePlayCollectionSuggest = function($inputs, options) {
            $inputs.each(function(index, element) {
                var self = this;
                alternatePlayCollection($(this), $.extend(true, {
                    validate: false,
                    select: function(e, data) {
                        $(self).parent().parent().find('span.hasConnectQitan').show();
                        var $input = $(e.currentTarget);
                        $input.data('value', data.item.qipuId);
                        //console.log( $input.data('value'));

                        var temp = data.item;
                        data.item = {};

                        data.item['qipuId'] = temp['qipuId'];
                        data.item['displayName'] = temp['displayName'];
                        data.item['contentType'] = temp['contentType'];
                        data.item['duration'] = temp['duration'];
                        data.item['needAlert'] = temp['needAlert'];
                        temp = {};

                        var alternatePlayCollection = $('input[name="alternatePlayCollection"]').val();
                        //console.log(alternatePlayCollection);
                        if (alternatePlayCollection) {
                            alternatePlayCollection = JSON.parse(alternatePlayCollection);
                            var has = false,
                                i;

                            for (var i in alternatePlayCollection) {
                                if (alternatePlayCollection[i].qipuId == data.item.qipuId) {
                                    has = 1;
                                    break;
                                }
                            }

                            i = parseInt(i) + 1;

                            if (!has) {
                                var msg = null;
                                if (data.item.needAlert == Ancestor.Config.APC_WARNING.RED) {
                                    msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端没有上线，但会在PPS平台播出，是否确认添加？";
                                } else if (data.item.needAlert == Ancestor.Config.APC_WARNING.ORANGE) {
                                    msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端有地域播控，但会在PPS平台全地域播出，是否确认添加？";
                                } else {
                                    alternatePlayCollection[i] = data.item;

                                    $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
                                    alternatePlayCollectionAppend({
                                        qipuId: data.item.qipuId
                                    });
                                }

                                if (msg) {
                                    SystemDialog.queryConfirm(msg, function(flag) {
                                        if (flag === true) {
                                            alternatePlayCollection[i] = data.item;

                                            $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));

                                            alternatePlayCollectionAppend({
                                                qipuId: data.item.qipuId
                                            });
                                        }
                                    });
                                }
                            }

                        } else {
                            alternatePlayCollection = {};

                            var msg = null;
                            if (data.item.needAlert == Ancestor.Config.APC_WARNING.RED) {
                                msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端没有上线，但会在PPS平台播出，是否确认添加？";
                            } else if (data.item.needAlert == Ancestor.Config.APC_WARNING.ORANGE) {
                                msg = "该节目【" + data.item.qipuId + " " + data.item.displayName + "】在PPS端有地域播控，但会在PPS平台全地域播出，是否确认添加？";
                            } else {
                                alternatePlayCollection[0] = data.item;

                                $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
                                alternatePlayCollectionAppend({
                                    qipuId: data.item.qipuId
                                });
                            }

                            if (msg) {
                                SystemDialog.queryConfirm(msg, function(flag) {
                                    if (flag === true) {
                                        alternatePlayCollection[0] = data.item;

                                        $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));

                                        alternatePlayCollectionAppend({
                                            qipuId: data.item.qipuId
                                        });
                                    }
                                });
                            }
                        }
                    },
                    onNoResult: function() {
                        $(self).parent().parent().find('span.hasConnectQitan').hide();
                    },
                    change: function(event, ui) {
                        if (null === ui.item) {
                            $(self).parent().parent().find('span.hasConnectQitan').hide();
                        }
                    }
                }, options));
            });
        };


        var alternatePlayCollectionAppend = function(v) {
            $('#alternatePlayCollectionIds').append('<span class="ui-suggest-value tagmanagerTag" data-id="' + v.qipuId + '">' + v.qipuId + '<a class="tagmanagerRemoveTag"  onclick="Ancestor.Util.removeAlternatePlayCollection(this)"  title="Remove" href="javascript:;">x</a></span>');
            $('input[name="alternatePlayCollectionInput"]').attr('disabled','disabled');;
        };

        // 删除备播库
        removeAlternatePlayCollection = function(obj) {

            var alternatePlayCollection = $('input[name="alternatePlayCollection"]').val(),
                AlternatePlayCollectionId = $(obj).parent().attr('data-id'),
                alternatePlayCollectionTmp = {};

            alternatePlayCollectionTmp = alternatePlayCollection = JSON.parse(alternatePlayCollection);

            for (var i in alternatePlayCollectionTmp) {
                if (alternatePlayCollectionTmp[i].qipuId == AlternatePlayCollectionId) {
                    delete alternatePlayCollection[i];
                    break;
                }
            }

            if ($.isEmptyObject(alternatePlayCollection)) {
                $('input[name="alternatePlayCollection"]').val('');
                $('input[name="alternatePlayCollectionInput"]').removeAttr('disabled');;
            } else {
                $('input[name="alternatePlayCollection"]').val(JSON.stringify(alternatePlayCollection));
            }

            $(obj).parent().remove();
        };



        var getAuth = function(str) {

            var auth = {
                    'sign': '',
                    'clientTime': '',
                    'from': ''
                },
                time = parseInt(new Date().getTime() / 1000);

            auth.from = Ancestor.Config.EPG_AUTH.From;
            auth.clientTime = time;
            auth.sign = md5(str + time + Ancestor.Config.EPG_AUTH.key);

            //console.log(auth);            
            return auth;

        };

        return {
            imageCrop: imageCrop,
            authorization: authorization,
            getParam: getParam,
            getUrlId: getUrlId,
            fillFieldNameWhenChangeSelect: fillFieldNameWhenChangeSelect,
            limitWordCount: limitWordCount,
            getUploadFiles: getUploadFiles,
            isNormal: isNormal,
            openDlg: openDlg,
            qitanSuggest: qitanSuggest,
            universalCodeSuggest: universalCodeSuggest,
            imageObjectEcho: imageObjectEcho,
            getAuth: getAuth,
            alternatePlayCollectionSuggest: alternatePlayCollectionSuggest,
            alternatePlayCollectionAppend: alternatePlayCollectionAppend,
            removeAlternatePlayCollection: removeAlternatePlayCollection,
        };


    })();

});